<template>
  <div class="left-card-container">
    <!-- 头部搜索和操作区域 -->
    <div class="header-section">
      <div class="section-title">
        {{ $t('sys.department.departmentList') }}
      </div>
      <div class="search-container">
        <el-input
          v-model="searchValue"
          :placeholder="$t('common.search')"
          class="search-input"
          size="default"
        >
          <template #prefix>
            <Search :size="18" />
          </template>
        </el-input>
      </div>
      <div class="actions-container">
        <el-dropdown trigger="click">
          <el-button class="action-button" size="small" text type="primary">
            展开
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="expandAllHandle('open')">
                {{ $t('sys.department.expandAll') }}
              </el-dropdown-item>
              <el-dropdown-item @click="expandAllHandle('close')">
                {{ $t('sys.department.collapseAll') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 树形组件区域 -->
    <div class="tree-section">
      <el-tree
        :key="treeKey"
        :data="options"
        :default-expand-all="isExpandAll"
        :props="defaultProps"
        class="department-tree"
        node-key="id"
        @node-click="searchDepartment"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@vben/icons';
import { $t } from '@vben/locales';

import { refreshDictOptions } from '#/hooks/useDictCache';

// 定义 emit 类型
interface Emit {
  (e: 'searchDepartment', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
const options = ref<any[]>([]); // 下拉数据
const treeKey = ref(1); // 必须绑定一个组件key,才能确保展开与收缩有效果！
const isExpandAll = ref<boolean>(false);
const treeOptions = ref<any[]>([]); // 临时保存一份树配置的数据,用于搜索
const searchValue = ref<string>(''); // 搜索框的值
const defaultProps = {
  children: 'children',
  label: 'label',
  id: 'id',
};
const searchDepartment = (data: any) => {
  emit('searchDepartment', data);
};
/** 展开与收缩 */
const expandAllHandle = async (type: string) => {
  nextTick(() => {
    treeKey.value = Date.now();
    type === 'open' ? (isExpandAll.value = true) : (isExpandAll.value = false); // 展开与收缩
  });
};

// const searchDepartment = (data: any) => {
//   emit('searchDepartment', data);
// };
// console.log(aa.value);

onMounted(async () => {
  options.value = await refreshDictOptions('department'); // 更新数据
  treeOptions.value = options.value; // 赋值给下拉数据
});

/**
 * 在树形数据中搜索匹配关键字的节点
 * @param treeData 要搜索的树形数据
 * @param keyword 搜索关键词
 * @returns 包含所有匹配节点的扁平化数组
 */
const searchNodes = (treeData: any, keyword: any) => {
  const searchNodesInTree = ref<any[]>([]); // 搜索结果

  const traverseAndSearch = (data: any) => {
    for (const item of data) {
      const { label, children } = item;
      if (label.includes(keyword)) {
        searchNodesInTree.value.push(item);
      }
      if (children) {
        traverseAndSearch(children); // 递归处理子节点
      }
    }
  };

  traverseAndSearch(treeData);
  return searchNodesInTree.value; // 返回处理后的结果
};
// // 确保下拉数据数据拿到
watch(
  () => searchValue.value,
  (val: any) => {
    options.value = searchNodes(treeOptions.value, val); // 监听搜索框的值
  },
);
</script>

<style scoped lang="scss">
// 响应式设计
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .search-container {
    max-width: none;
  }

  .actions-container {
    justify-content: center;
  }
}

.left-card-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.header-section {
  display: flex;
  gap: 16px;
  align-items: center;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  min-width: 80px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.search-container {
  flex: 1;
  max-width: 300px;
}

.search-input {
  :deep(.el-input__wrapper) {
    border-radius: 6px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }

  :deep(.el-input__prefix) {
    color: #909399;
  }
}

.actions-container {
  display: flex;
  align-items: center;
}

.action-button {
  padding: 8px;
  border-radius: 6px;

  &:hover {
    background-color: #f5f7fa;
  }
}

.tree-section {
  flex: 1;
  overflow: hidden;
}

.department-tree {
  :deep(.el-tree-node) {
    position: relative;

    &:not(:last-child)::after {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 1px;
      content: '';
      background: linear-gradient(90deg, #f0f0f0 0%, transparent 100%);
    }
  }

  :deep(.el-tree-node__content) {
    height: 40px;
    margin: 2px 0;
    border-radius: 6px;
    transition: all 0.2s ease;

    &:hover {
      background-color: #f5f7fa;
      transform: translateX(4px);
    }

    &.is-current {
      font-weight: 500;
      color: #1890ff;
      background-color: #e6f7ff;
    }
  }

  :deep(.el-tree-node__label) {
    font-size: 14px;
    color: #606266;
  }

  :deep(.el-tree-node__expand-icon) {
    font-size: 12px;
    color: #909399;
    transition: transform 0.2s ease;

    &.expanded {
      transform: rotate(90deg);
    }
  }

  :deep(.el-tree-node__icon) {
    margin-right: 8px;
    color: #409eff;
  }
}
</style>
